import { executeLogin, loginCheck } from "./login/login";
import {initial as gitdbInitial} from "gitee-simple-db";

export interface InitializeOption {
    accessToken?: string;
    nickName?: string
}

export async function initialize(options: InitializeOption = {}) {
    // TODO 增加一个模态框用于提示用户操作。
    let {accessToken, nickName} = options;
    try {
        await initialDataBase(accessToken)
        await executeLogin(nickName)
    } catch (e) {
        console.error(e)
        clearUserInfo(); // 初始化或登录异常时直接清理一次用户数据
        throw Error("APP INITIALIZE ERROR " + e.message)
    }
}

export async function initialDataBase(accessToken: string | null | undefined) {
    if (!accessToken) {
        accessToken = localStorage.getItem("$ACCESS_TOKEN")
        if (accessToken === null) {
            accessToken = undefined
        }
    }
    let result = await gitdbInitial({
        repo: 'database',
        owner: 'lhhcherry',
        access_token: accessToken,
    })

    if (accessToken) {
        localStorage.setItem("$ACCESS_TOKEN", accessToken)
    }
    return result;
}

export function clearUserInfo() {
    window.localStorage.removeItem("$NICK_NAME")
    window.localStorage.removeItem("$ACCESS_TOKEN")
}
